package cn.wellwan.service.Impl;

import cn.wellwan.commons.WellwanBusinessException;
import cn.wellwan.entity.User;
import cn.wellwan.service.UserService;
import cn.wellwan.service.WechatService;
import cn.wellwan.utils.HttpClient;
import cn.wellwan.utils.WechatURLBase;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class WechatServiceImpl implements WechatService {

    @Value("${applet.appid}")
    private String appId;

    @Value("${applet.secret}")
    private String secret;

    @Autowired
    private UserService userService;

//    @Autowired
//    private RedisUtil redisUtils;

    @Override
    public JSONObject decode(String code) {
        String url = WechatURLBase.getSessionKey(appId, secret, code);
        HttpClient httpClient = new HttpClient();
        JSONObject json = httpClient.getJSON(url);
        if (json != null) {
            String session_key = json.getString("session_key");
            String openId = json.getString("openid");
            long expires = json.getLongValue("expires_in");
            if (StringUtils.isEmpty(session_key) && StringUtils.isEmpty(openId)) {
                String errcode = json.getString("errcode");
                String errmsg = json.getString("errmsg");
                String message = String.format("获取小程序的sessionKey异常-->%s,%s", errcode, errmsg);
                throw new WellwanBusinessException(message);
            }
           return json;
        }
        return null;
    }

    @Override
    public Object decodeUserInfo(String encryptedData, String sessionkey, String iv) {
        HttpClient httpClient = new HttpClient();
        JSONObject userInfo = httpClient.getUserInfo(encryptedData, sessionkey, iv);
        return null;
    }
}
